package com.mvvm.start.base.utils


/**
 * @功能:
 * @User Lmy
 * @Creat 2021/9/17 10:16 上午
 * @Compony 永远相信美好的事情即将发生
 */
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities

/**
 * 实时监听网络状态变化的[ConnectivityManager.NetworkCallback]实现类
 *
 * @author Qu Yunshuo
 * @since 2021/7/10 5:38 下午
 */
class NetworkCallbackImpl : ConnectivityManager.NetworkCallback() {

    /**
     * 当前网络类型
     */
    var currentNetworkType = -1

    /**
     * 当前网络是否已连接
     */
    var isConnected = false



    /**
     * 连接成功
     */
    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        isConnected = true
    }

    /**
     * 连接断开
     */
    override fun onLost(network: Network) {
        super.onLost(network)
        isConnected = false
    }

    override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
        super.onCapabilitiesChanged(network, networkCapabilities)
        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            currentNetworkType = when {
                networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    NetworkCapabilities.TRANSPORT_WIFI
                }
                networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    NetworkCapabilities.TRANSPORT_CELLULAR
                }
                else -> {
                    NetworkCapabilities.TRANSPORT_WIFI
                }
            }
            when (currentNetworkType) {
                0 -> {
                    "当前连接为数据流量".toast()
                }
                1 -> {
                    "当前连接为wifi".toast()
                }
                else -> {
                    "当前没有网络连接".toast()
                }
            }
        }
    }
}